#include "stdafx.h"
#include "xKernel/IxLayoutHorizon.h"
#include "LayoutManager.h"

static const INT BEGIN_ID = 0x1000;

CxLayoutManager::CxLayoutManager()
    : m_nIndex(BEGIN_ID)
{
    CComPtr<IxLayout> spLayout;
    ::xCommon::CreateObjectByIID(__uuidof(IxLayoutHorizon), (void**)&spLayout);
    m_mapLayout.insert(std::make_pair(ELT_HORIZON, spLayout));
}

CxLayoutManager::~CxLayoutManager()
{
    m_mapLayout.clear();
}

HRESULT CxLayoutManager::GetLayout(INT nType, IxLayout** ppLayout)
{
    if (!ppLayout)  return E_POINTER;

    *ppLayout = NULL;

    LAYOUTMAP::iterator it = m_mapLayout.find(nType);
    if (it == m_mapLayout.end())
    {
        return E_FAIL;
    }

    CComPtr<IxLayout> spLayout = it->second;

    if (spLayout)
    {
        return spLayout->QueryInterface(__uuidof(IxLayout), (void**)ppLayout);
    }
    else
    {
        return E_FAIL;
    }
}

HRESULT CxLayoutManager::Register(IxLayout* pLayout, LPINT pnType)
{
    if (!pLayout || !pnType)
    {
        return E_POINTER;
    }

    *pnType = -1;

    LAYOUTMAP::iterator it = m_mapLayout.begin();
    while (it != m_mapLayout.end())
    {
        if (it->second == pLayout)
            break;
    }

    if (it != m_mapLayout.end())
    {
        m_mapLayout.insert(std::make_pair(++m_nIndex, pLayout));
        *pnType = m_nIndex;
        return S_OK;
    }
    else
    {
        ATLASSERT(!L"pLayout is already exist!");
        return E_FAIL;
    }
}

HRESULT CxLayoutManager::Unregister(IxLayout* pLayout, INT nType)
{
    LAYOUTMAP::iterator it = m_mapLayout.find(nType);
    if (it != m_mapLayout.end() && it->second == pLayout)
    {
        m_mapLayout.erase(it);
        return S_OK;
    }
    else
    {
        return E_FAIL;
    }
}
